# -*- coding: utf-8 -*-

# 匹配字符串模块
import re

# 模拟数据库
from faker import Faker

faker_handler = Faker(locale='zh_CN')

"""
  脱敏数据
"""
def desensitize_data(data):
  if re.match(r'^[\u4e00-\u9fa5]{2,4}$', data):
    # 中文姓名
    return re.sub(r'(?<=.{1}).', '*', data)
  elif re.match(r'^1\d{10}$', data):
    # 手机号码
    return re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', data)
  elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', data):
    # 电子邮箱
    return re.sub(r'(?<=\w)[^@]+(?=@)', lambda x: '*'*len(x.group(0)), data)
  elif re.match(r'^\d{15}$|^\d{17}([0-9]|X)$', data):
    # 身份证号
    return re.sub(r'(?<=\w{4})\w(?<=\w{4})', '*', data)
  elif re.match(r'^\d{16}|\d{19}$', data):
    # 银行卡号
    return re.sub(r'(?<=\d{4})(\d+)(?=\d{4})', lambda x: '*'*len(x.group(1)), data)
  elif re.match(r'^\d{4}\d{2}\d{2}$', data):
    # 出生日期
    return re.sub(r'(?<=\d{4})\d{2}', '**', data)
  else:
    return data

if __name__ == '__main__':
  name = faker_handler.name()
  mask_name = desensitize_data(name)
  print("desensitize data %s => %s" % (name, mask_name))

  phone = faker_handler.phone_number()
  mask_phone = desensitize_data(phone)
  print("desensitize data %s => %s" % (phone, mask_phone))

  email = faker_handler.email()
  mask_email = desensitize_data(email)
  print("desensitize data %s => %s" % (email, mask_email))

  id_card = faker_handler.ssn()
  mask_id_card = desensitize_data(id_card)
  print("desensitize data %s => %s" % (id_card, mask_id_card))

  bank_card = faker_handler.credit_card_number()
  mask_bank_card = desensitize_data(bank_card)
  print("desensitize data %s => %s" % (bank_card, mask_bank_card))

  birth_day = faker_handler.date_of_birth().strftime('%Y%m%d')
  mask_birth_day = desensitize_data(birth_day)
  print("desensitize data %s => %s" % (birth_day, mask_birth_day))
